package com.nest.WorkNest.act;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.nest.WorkNest.R;
import com.nest.WorkNest.adapter.OrderChangeAdapter;
import com.nest.WorkNest.api.XutilsPost;
import com.nest.WorkNest.entity.NewBulkOrder;
import com.nest.WorkNest.entity.ProductDetailCart;
import com.nest.WorkNest.tools.ParseUtils;
import com.nest.WorkNest.tools.Tool;
import com.nest.WorkNest.view.ListViewForScrollView;
import com.orhanobut.logger.Logger;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

public class OrderChangeAct extends BaseActivity implements OnClickListener {
    @Bind(R.id.tv_orderchange_addressname)
    TextView tvOrderchangeAddressname;
    @Bind(R.id.tv_orderchange_addresstel)
    TextView tvOrderchangeAddresstel;
    @Bind(R.id.tv_orderchange_address)
    TextView tvOrderchangeAddress;
    @Bind(R.id.tv_orderchange_productname)
    TextView tvOrderchangeProductname;
    @Bind(R.id.tv_orderchange_productId)
    TextView tvOrderchangeProductId;
    @Bind(R.id.tv_orderchange_totalnumber)
    TextView tvOrderchangeTotalnumber;
    @Bind(R.id.tv_orderchange_totalprice)
    TextView tvOrderchangeTotalprice;
    @Bind(R.id.btn_orderchange_submit)
    Button btnOrderchangeSubmit;
    @Bind(R.id.iv_orderchange_pic)
    ImageView ivOrderchangePic;
    private ListViewForScrollView lv_orderchangelist;
    private Context context = OrderChangeAct.this;
    private ArrayList<HashMap<String, String>> data = new ArrayList<>();
    private LayoutInflater lif;
    private ProductDetailCart productDetailCart;
    private String productId, productName, addressId, productType, requiredExplain,
            deliveryTime, deliveryWay, productimgUrl;
    private int minOrderNumber, optOrderNumber;
    private float totalprice, minquotation, optquotation;
    private NewBulkOrder newBulkOrder;
    private OrderChangeAdapter orderChangeAdapter;
    public BitmapUtils bitmapUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_orderchange);
        ButterKnife.bind(this);
        bitmapUtils = new BitmapUtils(context);
        initView();
    }

    public void initView() {
        Intent intent = getIntent();
        initProgress(context, "提交中...");
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (intent.getSerializableExtra("productDetailCart") != null) {
            productDetailCart = (ProductDetailCart) intent.getSerializableExtra("productDetailCart");
            addressId = intent.getStringExtra("addressId");
            data = productDetailCart.getGetdatalist();
            productId = intent.getStringExtra("productId");
            productName = intent.getStringExtra("productName");
            productType = intent.getStringExtra("productType");
            requiredExplain = intent.getStringExtra("requiredExplain");
            deliveryTime = intent.getStringExtra("deliveryTime");
            deliveryWay = intent.getStringExtra("deliveryWay");
            productimgUrl = intent.getStringExtra("productimgUrl");
            tvOrderchangeProductId.setText(productId);
            tvOrderchangeProductname.setText(productName);
            minOrderNumber = productDetailCart.getMinOrderNumber();
            minquotation = productDetailCart.getMinquotation();
            optquotation = productDetailCart.getOptquotation();
            optOrderNumber = productDetailCart.getOptOrderNumber();
            if (!TextUtils.isEmpty(productimgUrl)) {
                if (!productimgUrl.substring(0, 1).equals("h") && !productimgUrl.substring(0, 1).equals("H")) {
                    productimgUrl = "http://" + productimgUrl;
                }
            }
            Glide.with(context)
                    .load(productimgUrl)
                    .centerCrop()
                    .placeholder(R.drawable.empty_photo)
                    .crossFade()
                    .into(ivOrderchangePic);
        }
        loadAddressInfo();
        initBar();
        actionbar_side_name.setVisibility(View.VISIBLE);
        actionbar_side_name.setText("订单详情");
        ll_iv_actionbar_side_left.setVisibility(View.VISIBLE);
        back();
        orderChangeAdapter = new OrderChangeAdapter(context, data, sumhandker);
        lv_orderchangelist = (ListViewForScrollView) findViewById(R.id.lv_orderchange_list);
        lv_orderchangelist.setSelector(R.color.bg_transparent);
        lv_orderchangelist.setFocusable(false);
        lif = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View headView = lif.inflate(R.layout.itemhead_orderedit, null);
        lv_orderchangelist.addHeaderView(headView);
        lv_orderchangelist.setAdapter(orderChangeAdapter);
        btnOrderchangeSubmit.setOnClickListener(this);
    }

    Handler sumhandker = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {

                tvOrderchangeTotalprice.setText(msg.getData().getString("name"));
            }
        }

    };


    private void loadAddressInfo() {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                JSONObject jsonObject = Tool.getJsonObject(result);
                JSONArray jsonArray;
                if (Tool.getString(jsonObject, "resultCode").equals("0")) {
                    jsonArray = Tool.getJsonArray(result, "dataList");
                    data = Tool.getListMapByJsonArray(jsonArray);
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
                if (data.size() != 0) {
                    tvOrderchangeAddressname.setText("收货人: " + data.get(0).get("name"));
                    String address = "收货地址: " + data.get(0).get("province") + "省"
                            + data.get(0).get("city") + data.get(0).get("address");
                    tvOrderchangeAddress.setText(address);
                    tvOrderchangeAddresstel.setText("电话: " + data.get(0).get("cellPhone"));
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostAddressList(context, addressId, ioAuthCallBack);
    }

    public void loadBulkOrder(ArrayList<HashMap<String, String>> getdataList) {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                Logger.json(result);
                if (Tool.getString(result, "resultCode").equals("0")) {
                    String bulkOrderId = Tool.getString(result, "bulkOrderId");
                    String toPayId = Tool.getString(result, "toPayId");
                    Intent intent = new Intent(context, PaymentAct.class);
                    intent.putExtra("bulkOrderId", bulkOrderId);
                    intent.putExtra("totalprice", newBulkOrder.getTotalPrice());
                    intent.putExtra("toPayId", toPayId);
                    startActivity(intent);
                    if (pd.isShowing())
                        pd.cancel();
                    finish();

                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
                if (pd.isShowing())
                    pd.cancel();
            }

            @Override
            public void getDealException(HttpException httpException, String result) {
                Logger.json(result);
                showToast("提交错误");
                if (pd.isShowing())
                    pd.cancel();
            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {
                if (!pd.isShowing())
                    pd.show();
            }
        };
        xutilsPost.doPostBulkOrder(context, newBulkOrder, getdataList, ioAuthCallBack);
    }

    private void initDataList() {
        newBulkOrder = new NewBulkOrder();
        int all = 0;
        ArrayList<HashMap<String, String>> getdataList = new ArrayList<>();
        for (int i = 1; i < lv_orderchangelist.getCount(); i++) {
            HashMap<String, String> getdata = new HashMap<>();
            EditText editText = (EditText) lv_orderchangelist.getChildAt(i).findViewById(R.id.edtTxt_orderedit_number);
            TextView textView = (TextView) lv_orderchangelist.getChildAt(i).findViewById(R.id.tv_orderedit_style);
            String style = textView.getText().toString();
            String[] styles = style.split("/");
            String color = styles[0];
            String size = styles[1];
            String number = editText.getText().toString();
            getdata.put("color", color);
            getdata.put("size", size);
            getdata.put("number", number);
            getdataList.add(getdata);
        }
        for (int j = 0; j < getdataList.size(); j++) {
            all += ParseUtils.string2int(getdataList.get(j).get("number"));
        }
        if (all >= minOrderNumber && all < optOrderNumber) {
            totalprice = minquotation * all;
            newBulkOrder.setPerPrice(minquotation);
            newBulkOrder.setTotalPrice(totalprice);
        } else if (all >= optOrderNumber) {
            totalprice = optquotation * all;
            newBulkOrder.setPerPrice(optquotation);
            newBulkOrder.setTotalPrice(totalprice);
        }
        newBulkOrder.setTotalQuantity(all);
        newBulkOrder.setProductId(productId);
        newBulkOrder.setProductName(productName);
        newBulkOrder.setProductType(productType);
        newBulkOrder.setUserReceiveAddress(addressId);
        newBulkOrder.setRequiredExplain(requiredExplain);
        newBulkOrder.setDeliveryTime(deliveryTime);
        newBulkOrder.setDeliveryWay(deliveryWay);
        if (newBulkOrder != null) {
            if (!pd.isShowing())
                pd.show();
            loadBulkOrder(getdataList);
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_orderchange_submit:
                initDataList();
                break;
        }
    }

    public boolean onTouchEvent(MotionEvent event) {
        try {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                    manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.onTouchEvent(event);
    }


}
